package org.nimi317.web_gis.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.nimi317.web_gis.context.SecurityContextHolder;
import org.nimi317.web_gis.dao.ProvinceQualityDao;
import org.nimi317.web_gis.data.AreaCodeList;
import org.nimi317.web_gis.entity.Area;
import org.nimi317.web_gis.entity.ProvinceQuality;
import org.nimi317.web_gis.service.AreaService;
import org.nimi317.web_gis.service.ProvinceQualityService;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

/**
 * (ProvinceQuality)表服务实现类
 *
 * @author makejava
 * @since 2024-05-18 08:59:24
 */
@Service("provinceQualityService")
public class ProvinceQualityServiceImpl extends ServiceImpl<ProvinceQualityDao, ProvinceQuality> implements ProvinceQualityService {

    private final ThreadPoolTaskExecutor executor;

    private final AreaService areaService;

    private final AreaCodeList areaCodeList;

    public ProvinceQualityServiceImpl(ThreadPoolTaskExecutor executor, AreaService areaService, AreaCodeList areaCodeList) {
        this.executor = executor;
        this.areaService = areaService;
        this.areaCodeList = areaCodeList;
    }

    @Override
    public void updateProvinceQualityData() {
        List<Area> areas = areaService.list();
        Map<Integer, List<Area>> collect = areas.stream().collect(Collectors.groupingBy(Area::getProvinceId));
        LocalDateTime time = SecurityContextHolder.getLastTime();
        CountDownLatch latch = new CountDownLatch(collect.size());
        for (Map.Entry<Integer, List<Area>> entry : collect.entrySet()) {
            Integer provinceId = entry.getKey();
            List<Area> areaList = entry.getValue();
            executor.execute(() -> {
                try {
                    areaCodeList.updateProvinceQuality(provinceId, areaList, time);
                } finally {
                    latch.countDown();
                }
            });
        }
    }
}

